/**
 * 设置色值透明度：输入色值和透明度，返回符合透明度的新色值
 * 
 * @memberof color
 * 
 * @param {String} color 色值(必传)
 * <br />支持格式：hex,rgb,rgba
 * 
 * @param {Number} opacity 透明度(可选) 
 * <br />范围:0 - 1
 * 
 * @returns  rgba 格式色值
 * 
 * @example  
 * setColorOpacity('#fff',0.5); // rgba(255,255,255,0.5)
 */
function setColorOpacity(color, opacity) {
    let c = color;
    // to varify color format
    const regHex = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    const regRGB =
        /^rgb\(([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\)$/i;
    const regRGBA =
        /^rgba\(([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,([0-9]|[0-9][0-9]|25[0-5]|2[0-4][0-9]|[0-1][0-9][0-9])\,(1|1.0|0.[0-9])\)$/i;

    // if hex，transform to rgb
    if (regHex.test(c)) {
        c = c.length === 4 ? c + c.slice(1, 4) : c // #000 格式补全6位
        const red = parseInt("0x" + c.slice(1, 3))
        const green = parseInt("0x" + c.slice(3, 5))
        const yellow = parseInt("0x" + c.slice(5, 7))
        c = `rgb(${red},${green},${yellow})`
    }

    // if rgb，transform to  rgba
    if (regRGB.test(c)) {
        const rgb = c.match(regRGB);
        c = `rgba(${rgb[1]},${rgb[2]},${rgb[3]},1)`
    }

    // if rgba , return color with opacity
    if (regRGBA.test(c)) {
        const rgba = c.match(regRGBA);
        if (opacity || opacity === 0) {
            return `rgba(${rgba[1]},${rgba[2]},${rgba[3]},${opacity})`
        } else {
            return c
        }
    } else {
        return 'wrong color value'
    }
}
module.exports.setColorOpacity = setColorOpacity
